import { trigger } from '@/utils/generator/config'
import { isArray } from '@/utils'

export default function generateVueScriptString (conf) {
  const tempFile = `
<script>
  export default {
    created () {},
    mounted () {},
    ${genData(conf)}
    computed: {},
    watch: {},
    ${genMethods(conf)}
  }
</script>
`
  return tempFile
}

function buildDataModel (componentsConf) {
  return `{${componentsConf.reduce((total, conf) => {
    if (!conf.vModel) return total
    return `${total}${total ? ',' : ''}${conf.vModel}:${conf.defaultValue}`
  }, '')}}`
}

function buildDataRules (confs) {
  return `{${confs.reduce((total, conf) => {
    if (!conf.vModel) return total
    let rules = []
    if (conf.required) {
      const type = isArray(conf.defaultValue) ? 'type: \'array\',' : ''
      let message = isArray(conf.defaultValue) ? `请至少选择一个${conf.vModel}` : `${conf.label}不能为空`
      const required = `{ required: true,${type} message: '${message}' }`
      rules.push(required)
    }
    if (conf.regList && isArray(conf.regList)) {
      conf.regList.forEach(item => {
        if (item.pattern) {
          // eslint-disable-next-line no-eval
          rules.push(`{ pattern: ${eval(item.pattern)}, message: '${item.message}', trigger: '${trigger[conf.tag]}' }`)
        }
      })
    }
    return `${total}${total ? ',' : ''}${conf.vModel}:[${rules.join(',')}]`
  }, '')}}`
}

function genData ({ componentsConf, formConf }) {
  return `
    data(){
      return {
        ${formConf.model}:${buildDataModel(componentsConf)},
        ${formConf.rules}:${buildDataRules(componentsConf)}
      }
    }
  `
}

function genMethods () {

}
